#!/usr/bin/env bash

export ANSIBLE_HOST_KEY_CHECKING=False

echo "Install Start Time: "`date`
INSTALLBASEDIR=$(cd $(dirname $0);pwd)
CONFIG_FILE="${INSTALLBASEDIR}/config.yml"
#CUSTOM_FILE="${INSTALLBASEDIR}/custom.yml"
CUSTOM_FILE_RES="${INSTALLBASEDIR}/custom_result.yml"
INVENTORY_FILE="${INSTALLBASEDIR}/common/deploy/inventory.ini"
PLAYBOOK_FILE="${INSTALLBASEDIR}/common/deploy/site.yml"

cd ${INSTALLBASEDIR}

echo "清理缓存文件"
rm -rf ${INSTALLBASEDIR}/common/script/.cache
rm -rf ${CUSTOM_FILE_RES}
mkdir -p ${INSTALLBASEDIR}/common/script/.cache

#判断Python3目录在不在
PY3_DIR="${INSTALLBASEDIR}/common/open_source/python3920"
if [ ! -d "$PY3_DIR" ]; then
    echo "目录 $PY3_DIR 不存在，正在解压文件..."
    tar -xzvf "${PY3_DIR}.tar.gz" -C "${INSTALLBASEDIR}/common/open_source/"
    if [ $? -eq 0 ]; then
        echo "文件解压成功至 $PY3_DIR"
    else
        echo "解压失败，请检查压缩文件是否存在或格式是否正确。"
        exit 1
    fi
else
  echo "目录 $TARGET_DIR 已存在，无需解压。"
fi


echo "检查config.yml文件"
sh ${INSTALLBASEDIR}/common/script/check_config.sh
if [ $? -eq 1 ]; then
    #如果修改minio的9000端口，可以注释这里，让脚本继续执行
    exit 1
    #:
fi

echo "检查release_version"
release=$(rpm -qa |grep release |awk -F '-' '{print $1}' |egrep "centos|redhat|openEuler|neokylin|kylin|uos|almalinux|ctyunos|bclinux" |head -1)
echo "1.check local system version"
if [ "${release}" == "centos" ];then
    release_version=$(rpm -qa |grep centos-release |awk -F '-' '{print $3}' |head -1)
elif [ "${release}" == "redhat" ];then
    release_version=$(rpm -qa |grep redhat-release |awk -F '.' '{print $(NF-1)}' |sed 's/el//g' |head -1)
###龙蜥BCLinux-x86移动操作系统新增判断
elif [ "${release}" == "bclinux" ];then
    release_version=$(rpm -qa |grep bclinux-release |awk -F '-' '{print $3}'|awk -F '.' '{print $1}')
###ctyunos系统新增判断
elif [ "${release}" == "ctyunos" ];then
    release_version=$(if [ `rpm -qa |grep ctyunos-release |wc -l` -gt 0 ];then echo "7";fi )
###AlmaLinux新增判断
elif [ "${release}" == "almalinux" ];then
    release_version=$(if [ `rpm -qa |grep almalinux-release-8 |wc -l` -gt 0 ];then echo "7";fi)
###中标麒麟新增判断
elif [ "${release}" == "neokylin" ];then
    release_version=$(rpm -qa |grep neokylin-release |awk -F '[-.]' '{print $4}' |head -1)
###银河麒麟新增判断
elif [ "${release}" == "kylin" ];then
    release_version=$(if [ `rpm -qa |grep kylin-release-10 |wc -l` -gt 0 ];then echo "7";fi)
###统信OS新增判断
elif [ "${release}" == "uos" ];then
    release_version=$(if [ `rpm -qa |grep uos-release |wc -l` -gt 0 ];then echo "8";fi)
###欧拉系统新增判断
elif [ "${release}" == "openEuler" ];then
    release_version=$(if [ `rpm -qa |grep openEuler-release |wc -l` -gt 0 ];then echo "7";fi )
else
    echo "not support OS"
    exit 1
fi


echo "安装sshpass"
if [ $(rpm -qa |grep sshpass |wc -l) -eq 0 ] ; then
    if [ "$(id -u)" != "0" ]; then
        echo "Please use root privileges exec: "
        echo "sudo rpm -ivh ${INSTALLBASEDIR}/common/open_source/sshpass-1.06-2.el${release_version}.x86_64.rpm --nodeps"
        exit 1
    else
        rpm -ivh ${INSTALLBASEDIR}/common/open_source/sshpass-1.06-2.el${release_version}.x86_64.rpm --nodeps
    fi
fi


#根据config.xml生成inventory.ini
echo "生成ini清单文件"
rm -rf ${INVENTORY_FILE}
${INSTALLBASEDIR}/common/open_source/python3920/bin/python3 ${INSTALLBASEDIR}/common/script/config_to_ini.py ${CONFIG_FILE} ${INVENTORY_FILE}
if [ $? -eq 1 ]; then
    exit 1
fi
cat ${INVENTORY_FILE}
echo "欢迎使用脚本安装程序，请确认部署清单文件"
read -p "确认【y】: " answer
if [ $answer != "y" ]; then
    echo "已退出"
    exit 1
fi


#根据inventory.ini替换custom.yml,传入根路径、ini、custom
#echo "开始生成custom_resolved.yml"
#${INSTALLBASEDIR}/common/open_source/python3920/bin/python3 ${INSTALLBASEDIR}/common/script/replace_custom.py ${INSTALLBASEDIR} ${INVENTORY_FILE} ${CUSTOM_FILE}
#echo "完成生成custom_resolved.yml"

#根据inventory.ini创建custom_result.yml,如果主机不是22，需要修改
echo "开始生成custom_result.yml"
ansible-playbook -i ${INVENTORY_FILE} ${INSTALLBASEDIR}/common/script/ini_to_custom.yml -e "root_path=${INSTALLBASEDIR}" -e "ansible_port=22"
echo "完成生成${CUSTOM_FILE_RES}"
cat ${CUSTOM_FILE_RES}
read -p "确认【y】: " answer1
if [ ${answer1} != "y" ]; then
    echo "已退出"
    exit 1
fi

echo "开始安装组件"

#修改${CUSTOM_FILE_RES}
sed -i "/^open_middle_path/copen_middle_path: ${INSTALLBASEDIR}/common/open_middle"  ${CUSTOM_FILE_RES}
sed -i "/^release_version/crelease_version: ${release_version}"  ${CUSTOM_FILE_RES}

# 检查必要文件是否存在
for FILE in "$CONFIG_FILE" "${CUSTOM_FILE_RES}" "$INVENTORY_FILE" "$PLAYBOOK_FILE"; do
    if [ ! -f "$FILE" ]; then
        echo "错误: 文件 $FILE 不存在!"
        exit 1
    fi
done

#读取config.yml,统计完开始执行安装
config=$(grep -E "^- " ${CONFIG_FILE})
if [ -z "$config" ]; then
    echo "错误: 在 $CONFIG_FILE 中未找到有效的主机配置行!"
    exit 1
fi
# 统计组件数量
nginx_num=$(grep -w nginx <<< "$config" | wc -l) # 使用 -w 匹配整个单词
nacos_num=$(grep -w nacos <<< "$config" | wc -l)
mysql_num=$(grep -w mysql <<< "$config" | wc -l)
minio_num=$(grep -w minio <<< "$config" | wc -l)
redis_num=$(grep -w redis <<< "$config" | wc -l)
kibana_num=$(grep -w kibana <<< "$config" | wc -l)
zk_num=$(grep -w zookeeper <<< "$config" | wc -l)
kafka_num=$(grep -w kafka <<< "$config" | wc -l)
es_num=$(grep -w elasticsearch <<< "$config" | wc -l)
ck_num=$(grep -w clickhouse <<< "$config" | wc -l)
hadoop_num=$(grep -w hadoop <<< "$config" | wc -l)
jdk_num=$(grep -w jdk <<< "$config" | wc -l)

# 根据统计结果执行部署
deploy_component() {
    local component=$1
    local num=$2
    local tags=$3

    if [ "$num" -ne 0 ]; then
        echo "开始部署 $component..."
        if ansible-playbook -i "$INVENTORY_FILE" "$PLAYBOOK_FILE" -e "deploy_type=$component" -e "@$CUSTOM_FILE_RES" --tags "$tags" --force-handlers; then
            echo "$component 部署成功!"
	    sleep 3
        else
            echo "错误: $component 部署失败!"
            exit 1 # 部署失败则退出脚本
        fi
    else
        echo "跳过 $component 部署 (配置数量: $num)."
    fi
}

# 依次检查并部署各组件
deploy_component "elasticsearch" "$es_num" "deploy_es"
deploy_component "minio" "$minio_num" "deploy_minio"
deploy_component "redis" "$redis_num" "deploy_redis"
deploy_component "mysql" "$mysql_num" "deploy_mysql"
deploy_component "nacos" "$nacos_num" "deploy_nacos"
deploy_component "jdk" "$jdk_num" "deploy_jdk"
deploy_component "nginx" "$nginx_num" "deploy_nginx"
deploy_component "zookeeper" "$zk_num" "deploy_zk"
deploy_component "kafka" "$kafka_num" "deploy_kafka"
deploy_component "kibana" "$kibana_num" "deploy_kibana"
deploy_component "hadoop" "$hadoop_num" "deploy_hadoop"

# 特殊处理 ClickHouse 的部署 tags
case "$ck_num" in
    1) ck_tags="deploy_ck1" ;;
    3) ck_tags="deploy_ck3" ;;
    4) ck_tags="deploy_ck4" ;;
    6) ck_tags="deploy_ck6" ;;
    *) ck_tags="deploy_ck" ;; # 其他数量使用默认 tag
esac
deploy_component "clickhouse" "$ck_num" "$ck_tags"

if [ $nacos_num -ne 0 ]; then
  echo "执行替换nacos变量"
  sh ${INSTALLBASEDIR}/common/script/replace_nacos.sh
  echo "导入nacos配置"
  sh ${INSTALLBASEDIR}/common/script/import_nacos.sh
fi


echo "所有组件部署检查完成."
echo ""
echo "==================== 组件安装总结 ===================="
echo "Install End Time: "`date`
echo ""

# 调用独立的Python脚本生成组件总结
echo "正在生成组件安装总结..."
${INSTALLBASEDIR}/common/open_source/python3920/bin/python3 ${INSTALLBASEDIR}/common/script/summary.py ${CUSTOM_FILE_RES}
if [ $? -eq 0 ]; then
    echo "组件总结生成成功!"
else
    echo "警告: 组件总结生成失败，但安装已完成"
fi

echo ""
echo "======================================================"
